package com.shelpe.services.sinbad.controller;

import java.io.IOException;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonFormat.Shape;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.shelpe.services.sinbad.entity.jpa.Product;
import com.shelpe.services.sinbad.repository.jpa.ProductImageRepository;
import com.shelpe.services.sinbad.repository.jpa.ProductRepository;
import com.shelpe.services.sinbad.service.simbaproxy.ImageClient;
import com.shelpe.services.sinbad.service.simbaproxy.ImageClient.AddProductImgResponse;
import com.shelpe.services.sinbad.service.simbaproxy.ImageClient.ItemImg;
import com.shelpe.services.sinbad.service.simbaproxy.SimbaProxyBaseDto;
import com.shelpe.services.sinbad.utils.ImageInfo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/sinbadservice")
@Api("商品图片上传相关的API")
public class UploadImageController {

	@Autowired
	private ImageClient imageClient;
	@Autowired
	private ProductRepository productRepository;
	@Autowired
	private ProductImageRepository productImagesRepository;

	@ApiOperation("修改商品的图片")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "Content-Type", value="请求类型", defaultValue=MediaType.MULTIPART_FORM_DATA_VALUE, required = true, paramType = "header", dataType = "string"),
		@ApiImplicitParam(name = "token", value="app token", defaultValue="sh2015sh", required = true, paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "image", value="图片", required = true, paramType = "form", dataType = "file"),
		@ApiImplicitParam(name = "product_id", value="宝贝编号", defaultValue="527576380131", required = true, paramType = "path", dataType = "long"),
		@ApiImplicitParam(name = "image_id", value="图片编号", defaultValue="0", required = false, paramType = "query", dataType = "long")
	})
	@RequestMapping(method = RequestMethod.POST, path = "/products/{product_id}/images", consumes=MediaType.MULTIPART_FORM_DATA_VALUE + ";charset=UTF-8")
	public ImageDto updateProductImage(@PathVariable("product_id") long productId, 
			@RequestParam(name = "image_id", required=false, defaultValue = "0") long imgId,
			@RequestParam MultipartFile image) {
		log.info("upload image {} to product {} with image id {}", image.getOriginalFilename(), productId,imgId);
		
		Assert.isTrue(image != null, "image_is_null");
		Assert.isTrue(image.getSize() > 0, "image_is_no_size");
		
		Product product = this.productRepository.findOne(productId);
		Assert.notNull(product, "product_not_found");
		
		Assert.isTrue(product.getUserID() > 0, "invalid_user_id");
		
		ImageDto dto = new ImageDto();
		long userID = product.getUserID();
		
		try {
			ImageInfo info = new ImageInfo();
			info.setInput(image.getInputStream());
			boolean result = info.check();
			log.debug("check result: {} with {} format", result, info.getFormatName());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		AddProductImgResponse res = null;
					
		if(imgId > 0){
			res = imageClient.updateImg(userID, productId, imgId, image);
		}else{
			res = imageClient.addImg(userID, productId, image);
		}

		if (res == null) {
			dto.setError(new SimbaProxyBaseDto.Error());
			dto.getError().setCode(-1);
			dto.getError().setMessage("taobao_response_is_null");
			dto.getError().setSubMessage("淘宝返回为空,没有效数据");
			return dto;
		}
		if (res.getError() != null) {
			dto.setError(res.getError());
			log.error("fail to update product img: {}", "(原因为" + res.getError().getSubMessage() + ")");
			return dto;
		}
		if(res.getRes()!=null&&res.getRes().getItemImg()!=null){
			//TODO:更新图片
			
			ItemImg itemImg = res.getRes().getItemImg();
			dto.setImgUrl(itemImg.getImgUrl());
			dto.setImgId(itemImg.getImgId());
			dto.setCreated(dto.getCreated());
			productImagesRepository.updateImgUrl(itemImg.getImgUrl(), productId, itemImg.getImgId());
			return dto;
		}
		
		return dto;
	}
	
	@Data
	@JsonInclude(Include.NON_NULL)
	public static class ImageDto {
		@JsonProperty("id")
		private long imgId;
		@JsonProperty("url")
		private String imgUrl;		
		@JsonProperty("created")
		@JsonFormat(shape = Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "Asia/Shanghai")
		private Date created;
		private SimbaProxyBaseDto.Error error;
	}
	
}
